<?php
/**
 * Title: CN Scheduling
 * Description: Adds scheduling data tables (repeat schedule and open/close schedule) that can be attached to listings
 * Author: Jason Raede
 * Version: 0.4
 */
 
Plugin()->registerFilter('content_query_sql', 'schedulingSql');
Plugin()->registerFilter('content_query_date', 'schedulingDateClause');
Plugin()->registerFilter('content_query_datetime', 'schedulingDatetimeClause');
//register_function('listing_general_config', 'cn_scheduling_config_options');
//register_function('listing_general_config_request', 'cn_scheduling_update_options');


function cn_scheduling_day_string($string) {
	$switch = array('mon'=>1, 'tue'=>2, 'wed'=>3, 'thu'=>4, 'fri'=>5, 'sat'=>6, 'sun'=>7);
	$reverse = array(1=>'Mon', 2=>'Tue', 3=>'Wed', 4=>'Thu', 5=>'Fri', 6=>'Sat', 7=>'Sun');
	$days = array();
	
	for($i=1;$i<=7;$i++) {
		$day = substr($string, (3 * ($i - 1)), 3);
		if($day) $days[$i] = $day;
	}
		
	$range = array();
	
	foreach($days as $index=>$day) {	
		if($switch[$days[$index + 1]] - $switch[$day] == 1) {
			if(!$in_range) {
				$range_start = $switch[$day];
			}
			$in_range = TRUE;
		}
		else {		
			// Either end of range, or day by itself
			if($in_range && ($switch[$day] - $range_start > 1)) {
				$range[] = $reverse[$range_start] . ' - ' . $reverse[$switch[$day]];
			}
			elseif($in_range && ($switch[$day] - $range_start == 1)) {
				$range[] = $reverse[$range_start];
				$range[] = $reverse[$switch[$day]];
			}
			else {
				$range[] = $reverse[$switch[$day]];
			}
			$in_range = FALSE;
			$range_start = null;
		}
	}
	
	$count = count($range);
	
	switch($count) {
		case 1:
			return $range[0];
			break;
		case 2:
			return $range[0] . ', '.$range[1];
			break;
		default:
			$range[$count - 1] = '& '.$range[$count - 1];
			return implode(', ', $range);
			break;
	}
}

function cn_openclose_times($listing, $date, $return_format = 'g:ia') {
	global $cndb;
	$day = strtolower(date('D', strtotime(str_replace('-', '/', $date))));
	
	$row = $cndb->get_row("SELECT `oc_open`, `oc_close` FROM `cn_open_close_schedules` WHERE `oc_listing`='$listing' AND `oc_days` LIKE '%$day%'");
	
	if($return_format = 'U') {
		$open = (strtotime($row->oc_open) % (60*60*24));
		$close = (strtotime($row->oc_close) % (60*60*24));
		
		if($close < $open) $close += 60*60*24;
		return array($open, $close);
	}
	else {
		return array(date($return_format, strtotime($row->oc_open)), date($return_format, strtotime($row->oc_close)));
	}
}


function cn_scheduling_prepare_listing_data($content, $args) {
	$data_type = $args['data_type'];
	$listing = $args['listing'];
	$date = $args['arguments'];
	global $cndb;
	
	switch($data_type) {
		case 'Open/Close Schedule':
			/** Is there a query variable for date? If so, display only data for that day. If not, display all days */
			if(!$date) $date = get_query_var('date');
			if($date) {
				$day = strtolower(date('D', strtotime(str_replace('-', '/', $date))));
				
				$row = $cndb->get_row("SELECT `oc_open`, `oc_close` FROM `cn_open_close_schedules` WHERE `oc_listing`='$listing' AND `oc_days` LIKE '%$day%'");
				
				$return = date('g:ia', strtotime($row->oc_open)) . ' - '.date('g:ia', strtotime($row->oc_close));
			}
			else {
				$return = array();
				$results = $cndb->get_results("SELECT `oc_open`, `oc_close`, `oc_days` FROM `cn_open_close_schedules` WHERE `oc_listing`='$listing'");
				foreach($results as $result) {
					$return[] = cn_scheduling_day_string($result->oc_days) . ': ' . date('g:ia', strtotime($result->oc_open)) . ' - '.date('g:ia', strtotime($result->oc_close));
				}
				
				$return = implode('<br />', $return);
			}
			break;
		case 'Repeat Schedule':
			/** Is there a query variable for date? If so, display only data for that day. If not, display all days */
			if(!$date) $date = get_query_var('date');
			$time = get_query_var('time');
			if($date && $time) {
				$format = date('Y-m-d', strtotime($date)) . ' '. date('H:i:s', strtotime($time));
				$row = $cndb->get_row("SELECT `occurrence_start`, `occurrence_end` FROM `cn_rpt_occurrences` WHERE `occurrence_listing`='$listing' AND `occurrence_start` <= '$format' AND `occurrence_end` > '$format'"); 
				$return = date('g:ia', strtotime($row->occurrence_start)). ' - '.date('g:ia', strtotime($row->occurrence_end));
			}
			elseif($date) {
				$format = date('Y-m-d', strtotime($date));
				$row = $cndb->get_row("SELECT `occurrence_start`, `occurrence_end` FROM `cn_rpt_occurrences` WHERE `occurrence_listing`='$listing' AND DATE(`occurrence_start`) = '$format'");
				
				$return = date('g:ia', strtotime($row->occurrence_start)). ' - '.date('g:ia', strtotime($row->occurrence_end));
			}
			else {
				$schedules = $cndb->get_results("SELECT * FROM `cn_rpt_schedules` WHERE `rpt_listing`='$listing'");
				$repeats = array();
				
				foreach($schedules as $schedule) {
					$start = strtotime($schedule->rpt_start);
					switch($schedule->rpt_mode) {
						case 'monthly_day':
							$day_string = 'The '.date('jS', $start).' of every month';
							break;
						case 'monthly_nth':
							$day = date('l', $start);
							$num = date('j', $start);
							$nth = ceil($num / 7);
							
							$day_string = 'The '.add_nth_string($nth).' '.strtolower($day).' of every month';
							break;
						case 'yearly':
							$day_string = 'Every year on '.date('F jS');
							break;
						default:
							if(preg_match('/mon|tue|wed|thu|fri|sat|sun/', $schedule->rpt_mode)) {
								$day_string = cn_scheduling_day_string($schedule->rpt_mode);
							}
							else {
								$day_string = date('F jS');
							}
							break;
						
					}
					
					$time_string = date('g:ia', $start). ' - '.date('g:ia', strtotime($schedule->rpt_end));
					
					$repeats[] = $day_string . ': ' . $time_string;
					
				}
				$return = implode('<br />', $repeats);
			}
			break;
		default:
			$return = $content;
			break;
	}
	
	return $return;
}

function cn_handle_delete_listings($args) {
	global $cndb;
	$listings = $args['listings'];
	$listing_type = $args['listing_type'];
	
	$listings = "'".implode("', '", $listings)."'";
	$cndb->query("DELETE FROM `cn_rpt_schedules` WHERE `rpt_listing` IN ($listings)");
	$cndb->query("DELETE FROM `cn_rpt_occurrences` WHERE `occurrence_listing` IN ($listings)");
	$cndb->query("DELETE FROM `cn_open_close_schedules` WHERE `oc_listing` IN ($listings)");

}

function cn_scheduling_update_options($type) {
	global $cndb;
	if($_REQUEST['update_settings']) {
		if(cn_get_option('l'.$type.'_allow_rpt_schedules') != $_REQUEST['scheduling_allow_rpt']) {
			if($_REQUEST['scheduling_allow_rpt']) {
				$cndb->query("INSERT INTO `cn_listing_fields` (`lf_display_name`, `lf_column`, `lf_data_type`, `lf_ltype`) VALUES('Repeat Schedule', 'cn_scheduling_repeat', 'Repeat Schedule', '$type')");
			}
			else {
				$cndb->query("DELETE FROM `cn_listing_fields` WHERE `lf_data_type`='Repeat Schedule' AND `lf_ltype`='$type'");
			}
		}
		if(cn_get_option('l'.$type.'_allow_open_close_schedules') != $_REQUEST['scheduling_allow_open_close']) {
			if($_REQUEST['scheduling_allow_open_close']) {
			$cndb->query("INSERT INTO `cn_listing_fields` (`lf_display_name`, `lf_column`, `lf_data_type`, `lf_ltype`) VALUES('Open/Close Schedule', 'cn_scheduling_open_close', 'Open/Close Schedule', '$type')");
			}
			else {
				$cndb->query("DELETE FROM `cn_listing_fields` WHERE `lf_data_type`='Open/Close Schedule' AND `lf_ltype`='$type'");
			}
		}
		cn_set_option('l'.$type.'_allow_rpt_schedules', $_REQUEST['scheduling_allow_rpt']);
		cn_set_option('l'.$type.'_allow_open_close_schedules', $_REQUEST['scheduling_allow_open_close']);
	}
	
	
}

function schedulingDateClause($content, $args) {
	$date = date('Y-m-d H:i:s', $args['params']['date']);
	$field = $args['field'];
	switch($field->cf_data_type) {
		case 'RepeatSchedule':
			$return = "DATE(`occurrence_start`) = DATE('$date')";
			break;
		case 'OpenCloseSchedule':
			$day = strtolower(date('D', $args['params']['date']));
			$return = "`oc_days` LIKE '%$day%'";
			break;
	}
	return $return;
}

function schedulingDatetimeClause($content, $args) {
	$date = date('Y-m-d', $args['params']['date']).' '.date('H:i:s', $args['params']['time']);
	$field = $args['field'];
	switch($field->cf_data_type) {
		case 'RepeatSchedule':
			$return = "`occurrence_start` <= '$date' AND `occurrence_end` > '$date'";
			break;
		case 'OpenCloseSchedule':
			$day = strtolower(date('D', $args['params']['date']));
			$yesterday = strtolower(date('D', $args['params']['date']));
			$return = "(`oc_days` LIKE '%$day%' AND TIME(`oc_open`) <= TIME('$date') AND (TIME(`oc_open`) >= TIME(`oc_close`) OR TIME(`oc_close`) > TIME('$date'))) OR (`oc_days` LIKE '%$yesterday%' AND TIME(`oc_open`) >= TIME(`oc_close`) AND TIME('$date') < TIME(`oc_close`))";
			break;
	}
	return $return;
}

function cn_scheduling_config_options($type) {
	global $cndb;
	?>
	<h4>Scheduling Module</h4>
	<p>
		<label><input type="checkbox" name="scheduling_allow_rpt" <?php if(cn_get_option('l'.$type.'_allow_rpt_schedules')) echo 'checked="checked"'?>/> <?=ucwords($cndb->get_var("SELECT `lt_plural` FROM `cn_listing_types` WHERE `lt_id`='$type'"))?> can have attached repeat schedules</label>
	</p>
	<p>
		<label><input type="checkbox" name="scheduling_allow_open_close" <?php if(cn_get_option('l'.$type.'_allow_open_close_schedules')) echo 'checked="checked"'?>/> <?=ucwords($cndb->get_var("SELECT `lt_plural` FROM `cn_listing_types` WHERE `lt_id`='$type'"))?> can have attached open/close schedules</label>
	</p>
	<?php
}



function cn_scheduling_query($content, $args) {
	$type = $args['type'];
	$date = $args['date'];
	$time = $args['time'];
	$variable = $args['variable'];
	
	if($date || $time) {
		if($type) {
			if(!$variable) {
				$variable = "*, GROUP_CONCAT(`tag_id` SEPARATOR ', ') AS `listing_tags`";
			}
			return "SELECT $variable FROM `cn_rpt_occurrences` RIGHT JOIN `cn_listings` ON `occurrence_listing`=`listing_id` LEFT JOIN `cn_listing_tag_relations` ON `ltr_listing`=`listing_id` LEFT JOIN `cn_tags` ON `ltr_tag`=`tag_id` LEFT JOIN `cn_listing_type$type` ON `listing_id`=`l".$type."_id` LEFT JOIN `cn_open_close_schedules` ON `oc_listing`=`listing_id`";
		}
		else {
			if(!$variable) {
				$variable = "*, GROUP_CONCAT(`tag_id` SEPARATOR ', ') AS `listing_tags`";
			}
			return "SELECT $variable FROM `cn_rpt_occurrences` RIGHT JOIN `cn_listings` ON `occurrence_listing`=`listing_id` LEFT JOIN `cn_listing_tag_relations` ON `ltr_listing`=`listing_id` LEFT JOIN `cn_tags` ON `ltr_tag`=`tag_id` LEFT JOIN `cn_open_close_schedules` ON `oc_listing`=`listing_id`";
		}
		
	}
	else {
		return $content;
	}
}

function cn_scheduling_display_inputs($args) {
	$form_elements = $args;
	switch($form_elements['data_type']) {
		case 'Repeat Schedule':
			
			?>
			
			
			break;
		case 'Open/Close Schedule':?>
			
			<?php if($form_elements['display']) : ?>
			<fieldset>
			<legend><?=$form_elements['display']?> <?=$form_elements['ajax_buttons']?></legend>
			<div class="cn-scheduling-set">Closed on <label><?=$form_elements['elements']['mon_close']?> Mon</label>&nbsp;&nbsp;&nbsp;<label><?=$form_elements['elements']['tue_close']?> Tue</label>&nbsp;&nbsp;&nbsp;<label><?=$form_elements['elements']['wed_close']?> Wed</label>&nbsp;&nbsp;&nbsp;<label><?=$form_elements['elements']['thu_close']?> Thu</label>&nbsp;&nbsp;&nbsp;<label><?=$form_elements['elements']['fri_close']?> Fri</label>&nbsp;&nbsp;&nbsp;<label><?=$form_elements['elements']['sat_close']?> Sat</label>&nbsp;&nbsp;&nbsp;<label><?=$form_elements['elements']['sun_close']?> Sun</label></div>
			<?php endif;?>
			<?php $count = count($form_elements['elements']['schedules']);
			$n = $form_elements['current_num'];
			for($i=0;$i<$count;$i++) : $n++; $element = $form_elements['elements']['schedules'][$i];?>
				<div class="cn-oc-schedule">
				<h3>Schedule <?=$n?> <?php if($n > 1) : ?><input type="button" value="X" class="cn_scheduling_remove_openclose"/><?php endif;?></h3>
				
				<div class="cn-scheduling-set"><label><?=$element['mon']?> Mon</label>&nbsp;&nbsp;&nbsp;<label><?=$element['tue']?> Tue</label>&nbsp;&nbsp;&nbsp;<label><?=$element['wed']?> Wed</label>&nbsp;&nbsp;&nbsp;<label><?=$element['thu']?> Thu</label>&nbsp;&nbsp;&nbsp;<label><?=$element['fri']?> Fri</label>&nbsp;&nbsp;&nbsp;<label><?=$element['sat']?> Sat</label>&nbsp;&nbsp;&nbsp;<label><?=$element['sun']?> Sun</label><br />
				From <?=$element['open']?> to <?=$element['close']?>
				
				</div>
				</div>

			<?php
			endfor;
			echo $form_elements['field_footer'];
			if($form_elements['display']) echo '</fieldset>';
			break;
	}
}

function cn_scheduling_validate_data($content, $args) {
	$field = $args['field'];
	$required = $field->lf_required;
	switch($field->lf_data_type) {
		case 'Repeat Schedule':
			$startdates = $_REQUEST[$field->lf_column . '_startdate'];
			$starttimes = $_REQUEST[$field->lf_column . '_starttime'];
			$endtimes = $_REQUEST[$field->lf_column . '_endtime'];
			$rpt_fors = $_REQUEST[$field->lf_column.'_rpt_for'];
			$rpt_units = $_REQUEST[$field->lf_column.'_rpt_unit'];
			
			$mons = $_REQUEST[$field->lf_column . '_rpt_mon'];
			$tues = $_REQUEST[$field->lf_column . '_rpt_tue'];
			$weds = $_REQUEST[$field->lf_column . '_rpt_wed'];
			$thus = $_REQUEST[$field->lf_column . '_rpt_thu'];
			$fris = $_REQUEST[$field->lf_column . '_rpt_fri'];
			$sats = $_REQUEST[$field->lf_column . '_rpt_sat'];
			$suns = $_REQUEST[$field->lf_column . '_rpt_sun'];
			
			$count = count($startdates);
			if($required) {
				if(!$startdates[0] || !$starttimes[0] || !$endtimes[0]) $content['errors'][] = $field->lf_display_name . ' - At least one repeat schedule is required.';
			}
			for($i=0;$i<$count;$i++) {
				if($startdates[$i] && $starttimes[$i] && $endtimes[$i]) {
					$startdate = $startdates[$i];
					$starttime = $starttimes[$i];
					$endtime = $endtimes[$i];
					$type = $_REQUEST[$field->lf_column . '_rpt_type'.$i];
					$rpt_for = $rpt_fors[$i];
					$rpt_unit = $rpt_units[$i];
					$mon = $mons[$i];
					$tue = $tues[$i];
					$wed = $weds[$i];
					$thu = $thus[$i];
					$fri = $fris[$i];
					$sat = $sats[$i];
					$sun = $suns[$i];
					
					/** Validate dates and times */
					$rptstart = strtotime($startdate . ' '.$starttime);
					$rptend = strtotime($endtime);
					
					/** If start is after end, the end is the next day. Otherwise, same day */
					if(strtotime($starttime) >= $rptend) {
						$rptend = strtotime($startdate . ' '.$endtime) + 60*60*24;
					}
					else {
						$rptend = strtotime($startdate . ' '.$endtime);
					}
					
					if(!$rptstart) {
						$content['errors'][] = $field->lf_display_name . $i.' - Starting date and/or starting time are invalid.';
					}
					if(!$rptend) {
						$content['errors'][] = $field->lf_display_name . $i.' - Ending time is invalid.';
					}
				
					$content['db_fields'][$field->lf_column .'_rptstart'][$i] = date('Y-m-d H:i:s', $rptstart);
					$content['db_fields'][$field->lf_column .'_rptend'][$i] = date('Y-m-d H:i:s', $rptend);
						
					/** Now check repeat modes */
					
					if($type == 'every') {
					
						/** Make sure they pressed at least one checkbox */			
							
						$rptmode = $mon.$tue.$wed.$thu.$fri.$sat.$sun;
						if(!$rptmode) {
							$content['errors'][] = $field->lf_display_name . $i.' - You must check at least one day to repeat on.';
						}
					}
					else {
						$rptmode = $type;
					}
					$content['db_fields'][$field->lf_column . '_rptmode'][$i] = $rptmode;
				
					if($type) {
						/** Make sure rpt_for is numeric */
						if(!is_numeric($rpt_for)) {
							$content['errors'][] = $field->lf_display_name . $i.' - Please enter a valid number of '.strtolower($rpt_unit) . ' to repeat for.';
						}
						$content['db_fields'][$field->lf_column . '_rptfor'][$i] = $rpt_for;
						$content['db_fields'][$field->lf_column . '_rptunit'][$i] = $rpt_unit;
					}
				}
			}
			break;
		case 'Open/Close Schedule':
			/** Required doesn't mean anything because it could be closed every day... */
			/** Just check to see if they clicked on a set of days, the times are valid */
			$mon = $_REQUEST[$field->lf_column . '_mon'];
			$tue = $_REQUEST[$field->lf_column . '_tue'];
			$wed = $_REQUEST[$field->lf_column . '_wed'];
			$thu = $_REQUEST[$field->lf_column . '_thu'];
			$fri = $_REQUEST[$field->lf_column . '_fri'];
			$sat = $_REQUEST[$field->lf_column . '_sat'];
			$sun = $_REQUEST[$field->lf_column . '_sun'];
			
					
			$days = array();
			$open = $_REQUEST[$field->lf_column.'_open'];
			$close = $_REQUEST[$field->lf_column.'_close'];
					
					
			$values = array('mon'=>$mon, 'tue'=>$tue, 'wed'=>$wed, 'thu'=>$thu, 'fri'=>$fri, 'sat'=>$sat, 'sun'=>$sun);
			foreach($values as $day=>$set) {
				$days[$set][] = $day;
			}
					
			/** Validate times */
			$max = count($open);
			for($i=0;$i<$max;$i++) {
				if(count($days[$i + 1])) {
					if(!$open[$i] || !$close[$i]) {
						$content['errors'][] = $field->lf_display_name . ' - Set '.($i + 1).': Starting time and/or ending time are invalid';
					}
					$content['db_fields'][$field->lf_column . '_open'][$i] = date('H:i:s', strtotime($open[$i]));
					$content['db_fields'][$field->lf_column . '_close'][$i] = date('H:i:s', strtotime($close[$i]));
					$content['db_fields'][$field->lf_column . '_days'][$i] = implode('', $days[$i + 1]);
				}
				else {
					$content['db_fields'][$field->lf_column . '_open'][$i] = '00:00:00';
					$content['db_fields'][$field->lf_column . '_close'][$i] = '00:00:00';	
					$content['db_fields'][$field->lf_column . '_days'][$i + 1] = '';
				}
						
			}
					
					
			break;
	}
	return $content;
}

function cn_scheduling_build_inputs($content, $args) {
	global $cndb;
	$listing = $args['listing'];
	$field = $args['field'];
	$current_num = $args['current_num'];
	$column = $field->lf_column;
	switch($field->lf_data_type) {
		case 'Repeat Schedule':
			/** Is it an AJAX request to display a new repeat schedule? */
			if($current_num) {
				
				$num = $current_num + 1;
				$min = $current_num;
			}
			else {
				/** Get number of repeat schedules. First priority is REQUEST, second is listing */
				$schedules = $cndb->get_results("SELECT * FROM `cn_rpt_schedules` WHERE `rpt_listing`='$listing'");
				$min = 0;
				$num = count($_REQUEST[$column.'_startdate']);
				if(!$num) $num = count($schedules);
				if(!$num) $num = 1;
				$ajax_buttons = '<input type="button" id="cn_scheduling_add_repeat" value="+"/>';
				$field_footer = '<div id="cn_scheduling_extra_repeats"></div>';
			}
			
			
			$form_elements = array('column'=>$field->lf_column, 'display'=>$field->lf_display_name, 'data_type'=>$field->lf_data_type, 'ajax_buttons'=>$ajax_buttons, 'field_footer'=>$field_footer, 'current_num'=>$current_num, 'elements'=>array());
			
			for($i=$min;$i<$num;$i++) {
				$row = $schedules[$i];
				$startdate = ($_REQUEST[$column.'_startdate'][$i]) ? $_REQUEST[$column.'_startdate'][$i] : ((strtotime($row->rpt_start) > 0) ? date('m/d/Y', strtotime($row->rpt_start)) : '');
				$starttime = ($_REQUEST[$column.'_starttime'][$i]) ? $_REQUEST[$column.'_starttime'][$i] : ((strtotime($row->rpt_start) > 0) ? date('h:iA', strtotime($row->rpt_start)) : '');
				$endtime = ($_REQUEST[$column.'_endtime'][$i]) ? $_REQUEST[$column.'_endtime'][$i] : ((strtotime($row->rpt_end) > 0) ? date('h:iA', strtotime($row->rpt_end)) : '');
				$rpt_none = 'checked="checked"';
				$rpt_daily = ($_REQUEST[$column.'_rpt_type'.$i] == 'daily') ? 'checked="checked"' : (($row->rpt_mode == 'daily') ? 'checked="checked"' : '');
				$rpt_every = ($_REQUEST[$column.'_rpt_type'.$i] == 'every') ? 'checked="checked"' : ((preg_match('/mon|tue|wed|thu|fri|sat|sun/', $row->rpt_mode)) ? 'checked="checked"' : '');
				
				$rpt_mon = ($_REQUEST[$column.'_rpt_mon'][$i] == 'mon') ? 'checked="checked"' : ((strstr($row->rpt_mode, 'mon') && $row->rpt_mode != 'monthly_day' && $row->rpt_mode != 'monthly_nth') ? 'checked="checked"' : '');
				$rpt_tue = ($_REQUEST[$column.'_rpt_tue'][$i] == 'tue') ? 'checked="checked"' : ((strstr($row->rpt_mode, 'tue')) ? 'checked="checked"' : '');
				$rpt_wed = ($_REQUEST[$column.'_rpt_wed'][$i] == 'wed') ? 'checked="checked"' : ((strstr($row->rpt_mode, 'wed')) ? 'checked="checked"' : '');
				$rpt_thu = ($_REQUEST[$column.'_rpt_thu'][$i] == 'thu') ? 'checked="checked"' : ((strstr($row->rpt_mode, 'thu')) ? 'checked="checked"' : '');
				$rpt_fri = ($_REQUEST[$column.'_rpt_fri'][$i] == 'fri') ? 'checked="checked"' : ((strstr($row->rpt_mode, 'fri')) ? 'checked="checked"' : '');
				$rpt_sat = ($_REQUEST[$column.'_rpt_sat'][$i] == 'sat') ? 'checked="checked"' : ((strstr($row->rpt_mode, 'sat')) ? 'checked="checked"' : '');
				$rpt_sun = ($_REQUEST[$column.'_rpt_sun'][$i] == 'sun') ? 'checked="checked"' : ((strstr($row->rpt_mode, 'sun')) ? 'checked="checked"' : '');
				
				$rpt_monthly_nth = ($_REQUEST[$column.'_rpt_type'.$i] == 'monthly_nth') ? 'checked="checked"' : (($row->rpt_mode == 'monthly_nth') ? 'checked="checked"' : '');
				
				$rpt_monthly_day = ($_REQUEST[$column.'_rpt_type'.$i] == 'monthly_day') ? 'checked="checked"' : (($row->rpt_mode == 'monthly_day') ? 'checked="checked"' : '');
				$rpt_yearly = ($_REQUEST[$column.'_rpt_type'.$i] == 'yearly') ? 'checked="checked"' : (($row->rpt_mode == 'yearly') ? 'checked="checked"' : '');
				
				$rpt_for = ($_REQUEST[$column.'_rpt_for'][$i]) ? $_REQUEST[$column.'_rpt_for'][$i] : $row->rpt_for;
				
				$rpt_unit_days = ($_REQUEST[$column.'_rpt_unit'][$i] == 'DAY') ? ' selected="selected"' : (($row->rpt_unit == 'DAY') ? ' selected="selected"' : '');
				$rpt_unit_weeks = ($_REQUEST[$column.'_rpt_unit'][$i] == 'WEEK') ? ' selected="selected"' : (($row->rpt_unit == 'WEEK') ? ' selected="selected"' : '');
				$rpt_unit_months = ($_REQUEST[$column.'_rpt_unit'][$i] == 'MONTH') ? ' selected="selected"' : (($row->rpt_unit == 'MONTH') ? ' selected="selected"' : '');
				$rpt_unit_years = ($_REQUEST[$column.'_rpt_unit'][$i] == 'YEAR') ? ' selected="selected"' : (($row->rpt_unit == 'YEAR') ? ' selected="selected"' : '');
				
				$form_elements['elements'][] = array(
						'startdate'=>
							sprintf('<input type="text" value="%s" name="%s" id="%s" class="datepicker cn-rpt-schedule-marker"/>', $startdate, $column.'_startdate[]', $column.'_startdate'.$i),
						'starttime'=>
							sprintf('<input type="text" value="%s" name="%s" id="%s" class="timepicker"/>', $starttime, $column.'_starttime[]', $column.'_starttime'.$i),
						'endtime'=>
							sprintf('<input type="text" value="%s" name="%s" id="%s" class="timepicker"/>', $endtime, $column.'_endtime[]', $column.'_endtime'.$i),
						
						'rpt_none'=>
							sprintf('<input type="radio" %s name="%s" id="%s" value=""/>', $rpt_none, $column.'_rpt_type'.$i, $column.'_rpt_none'.$i),
						'rpt_every'=>
							sprintf('<input type="radio" %s name="%s" id="%s" value="every"/>', $rpt_every, $column.'_rpt_type'.$i, $column.'_rpt_every'.$i),
						'rpt_mon'=>
							sprintf('<input type="checkbox" %s name="%s" id="%s" value="mon"/>', $rpt_mon, $column.'_rpt_mon[]', $column.'_rpt_mon'.$i),
						'rpt_tue'=>
							sprintf('<input type="checkbox" %s name="%s" id="%s" value="tue"/>', $rpt_tue, $column.'_rpt_tue[]', $column.'_rpt_tue'.$i),
						'rpt_wed'=>
							sprintf('<input type="checkbox" %s name="%s" id="%s" value="wed"/>', $rpt_wed, $column.'_rpt_wed[]', $column.'_rpt_wed'.$i),
						'rpt_thu'=>
							sprintf('<input type="checkbox" %s name="%s" id="%s" value="thu"/>', $rpt_thu, $column.'_rpt_thu[]', $column.'_rpt_thu'.$i),
						'rpt_fri'=>
							sprintf('<input type="checkbox" %s name="%s" id="%s" value="fri"/>', $rpt_fri, $column.'_rpt_fri[]', $column.'_rpt_fri'.$i),
						'rpt_sat'=>
							sprintf('<input type="checkbox" %s name="%s" id="%s" value="sat"/>', $rpt_sat, $column.'_rpt_sat[]', $column.'_rpt_sat'.$i),
						'rpt_sun'=>
							sprintf('<input type="checkbox" %s name="%s" id="%s" value="sun"/>', $rpt_sun, $column.'_rpt_sun[]', $column.'_rpt_sun'.$i),
						
						'rpt_weekly'=>
							sprintf('<input type="radio" %s name="%s" id="%s" value="weekly"/>', $rpt_weekly, $column.'_rpt_type'.$i, $column.'_rpt_weekly'.$i),
						'rpt_monthly_nth'=>
							sprintf('<input type="radio" %s name="%s" id="%s" value="monthly_nth"/>', $rpt_monthly_nth, $column.'_rpt_type'.$i, $column.'_rpt_monthly_nth'.$i),
						'rpt_monthly_day'=>
							sprintf('<input type="radio" %s name="%s" id="%s" value="monthly_day"/>', $rpt_monthly_day, $column.'_rpt_type'.$i, $column.'_rpt_monthly_day'.$i),
						'rpt_yearly'=>
							sprintf('<input type="radio" %s name="%s" id="%s" value="yearly"/>', $rpt_yearly, $column.'_rpt_type'.$i, $column.'_rpt_yearly'.$i),
						
						'rpt_for'=>
							sprintf('<input type="text" value="%s" name="%s" id="%s" class="short-text"/>', $rpt_for, $column.'_rpt_for[]', $column.'_rpt_for'.$i),
						'rpt_unit'=>
							sprintf('<select name="%s" id="%s" class="repeat-unit"><option %s value="DAY">Days</option><option %s value="WEEK">Weeks</option><option %s value="MONTH">Months</option><option %s value="YEAR">Years</option></select>', $column.'_rpt_unit[]', $column.'_rpt_unit'.$i,$rpt_unit_days, $rpt_unit_weeks, $rpt_unit_months, $rpt_unit_years)
				);
			}
			break;
		case 'Open/Close Schedule':
			/** Is it an AJAX request to display a new open/close schedule? */
			if($current_num) {
				$num = $current_num + 1;
				$min = $current_num + 1;
			}
			else {
				/** Get number of open/close schedules. First priority is REQUEST, second is listing */
				$schedules = $cndb->get_results("SELECT * FROM `cn_open_close_schedules` WHERE `oc_listing`='$listing'");
				$min = 1;
				$num = count($_REQUEST[$column.'_open']);
				
				if(!$num) $num = count($schedules);
				if(!$num) $num = 1;
				$ajax_buttons = '<input type="button" id="cn_scheduling_add_openclose" value="+"/>';
				$field_footer = '<div id="cn_scheduling_extra_openclose"></div>';
			}
			
			
			$form_elements = array('column'=>$field->lf_column, 'display'=>$field->lf_display_name, 'data_type'=>$field->lf_data_type, 'ajax_buttons'=>$ajax_buttons, 'field_footer'=>$field_footer, 'current_num'=>$current_num, 'elements'=>array());
			$form_elements['elements']['mon_close'] = sprintf('<input type="radio" name="%s" id="%s" value="" checked="checked"/>', $column.'_mon', $column.'_mon_close');
			$form_elements['elements']['tue_close'] = sprintf('<input type="radio" name="%s" id="%s" value="" checked="checked"/>', $column.'_tue', $column.'_tue_close');
			$form_elements['elements']['wed_close'] = sprintf('<input type="radio" name="%s" id="%s" value="" checked="checked"/>', $column.'_wed', $column.'_wed_close');
			$form_elements['elements']['thu_close'] = sprintf('<input type="radio" name="%s" id="%s" value="" checked="checked"/>', $column.'_thu', $column.'_thu_close');
			$form_elements['elements']['fri_close'] = sprintf('<input type="radio" name="%s" id="%s" value="" checked="checked"/>', $column.'_fri', $column.'_fri_close');
			$form_elements['elements']['sat_close'] = sprintf('<input type="radio" name="%s" id="%s" value="" checked="checked"/>', $column.'_sat', $column.'_sat_close');
			$form_elements['elements']['sun_close'] = sprintf('<input type="radio" name="%s" id="%s" value="" checked="checked"/>', $column.'_sun', $column.'_sun_close');
			
			for($i=$min;$i<=$num;$i++) {
				
				$row = $schedules[$i-1];
				$open = ($_REQUEST[$column.'_open'][$i-1]) ? $_REQUEST[$column.'_open'][$i-1] : ((strtotime($row->oc_open) > 0) ? date('h:iA', strtotime($row->oc_open)) : '');
				$close = ($_REQUEST[$column.'_close'][$i-1]) ? $_REQUEST[$column.'_close'][$i-1] : ((strtotime($row->oc_close) > 0) ? date('h:iA', strtotime($row->oc_close)) : '');
					
				$mon = ($_REQUEST[$column.'_mon'] == $i) ? 'checked="checked"' : ((strstr($row->oc_days, 'mon')) ? 'checked="checked"' : '');
				$tue = ($_REQUEST[$column.'_tue'] == $i) ? 'checked="checked"' : ((strstr($row->oc_days, 'tue')) ? 'checked="checked"' : '');
				$wed = ($_REQUEST[$column.'_wed'] == $i) ? 'checked="checked"' : ((strstr($row->oc_days, 'wed')) ? 'checked="checked"' : '');
				$thu = ($_REQUEST[$column.'_thu'] == $i) ? 'checked="checked"' : ((strstr($row->oc_days, 'thu')) ? 'checked="checked"' : '');
				$fri = ($_REQUEST[$column.'_fri'] == $i) ? 'checked="checked"' : ((strstr($row->oc_days, 'fri')) ? 'checked="checked"' : '');
				$sat = ($_REQUEST[$column.'_sat'] == $i) ? 'checked="checked"' : ((strstr($row->oc_days, 'sat')) ? 'checked="checked"' : '');
				$sun = ($_REQUEST[$column.'_sun'] == $i) ? 'checked="checked"' : ((strstr($row->oc_days, 'sun')) ? 'checked="checked"' : '');
				$form_elements['elements']['schedules'][] = array(
					'open' => sprintf('<input type="text" value="%s" name="%s" id="%s" class="timepicker cn-oc-schedule-marker"/>', $open, $column.'_open[]',  $column.'_open'.$i),
					'close' => sprintf('<input type="text" value="%s" name="%s" id="%s" class="timepicker"/>', $close, $column.'_close[]', $column.'_off'.$i),
					'mon' => sprintf('<input type="radio" %s name="%s" id="%s" value="%d"/>', $mon, $column.'_mon', $column.'_mon'.$i, $i),
					'tue' => sprintf('<input type="radio" %s name="%s" id="%s" value="%d"/>', $tue, $column.'_tue', $column.'_tue'.$i, $i),
					'wed' => sprintf('<input type="radio" %s name="%s" id="%s" value="%d"/>', $wed, $column.'_wed', $column.'_wed'.$i, $i),
					'thu' => sprintf('<input type="radio" %s name="%s" id="%s" value="%d"/>', $thu, $column.'_thu', $column.'_thu'.$i, $i),
					'fri' => sprintf('<input type="radio" %s name="%s" id="%s" value="%d"/>', $fri, $column.'_fri', $column.'_fri'.$i, $i),
					'sat' => sprintf('<input type="radio" %s name="%s" id="%s" value="%d"/>', $sat, $column.'_sat', $column.'_sat'.$i, $i),
					'sun' => sprintf('<input type="radio" %s name="%s" id="%s" value="%d"/>', $sun, $column.'_sun', $column.'_sun'.$i, $i));
			}
			break;
		default:
			$form_elements = $content;
			break;
	}

	return $form_elements;
}

function cn_form_ajax_add_rpt_schedule() {
	$current_num = $_REQUEST['schedules_amount'];
	$field = new stdClass;
	$field->lf_data_type = 'Repeat Schedule';
	$field->lf_column = 'cn_scheduling_repeat';
	$args = array('field'=>$field, 'current_num'=>$current_num);
	$build = cn_scheduling_build_inputs(null, $args);
	cn_scheduling_display_inputs($build);

}

function cn_form_ajax_add_openclose_schedule() {
	$current_num = $_REQUEST['schedules_amount'];
	$field = new stdClass;
	$field->lf_data_type = 'Open/Close Schedule';
	$field->lf_column = 'cn_scheduling_open_close';
	$args = array('field'=>$field, 'current_num'=>$current_num);
	$build = cn_scheduling_build_inputs(null, $args);
	cn_scheduling_display_inputs($build);

}

function cn_scheduling_datetime_sql($content, $args) {
	$data_type = $args['data_type'];
	switch($data_type) {
		case 'Repeat Schedule':
			$return = "`occurrence_start` <= '$mysql_datetime' AND `occurrence_end >= '$mysql_datetime'";
			break;		
		case 'Open/Close Schedule':
			$day = strtolower(date('D', $unix_datetime));
			$yesterday = strtolower(date('D', $unix_datetime - 60*60*24));
						
			$today_query = "`oc_days` LIKE '%$day%'";
						
			$today_time = "(TIME(`oc_open`) > TIME(`oc_close`) AND TIME('$mysql_datetime') >= TIME(`oc_open`)) OR (TIME(`oc_open`) < TIME(`oc_close`) AND TIME('$mysql_datetime') >= TIME(`oc_open`) OR TIME('$mysql_datetime') < TIME(`oc_close`))";
						
						
			$yesterday_query = "`oc_days` LIKE '%$yesterday%'";
						
			$yesterday_time = "TIME(`oc_open`) > TIME(`oc_close`) AND TIME('$mysql_datetime') < TIME(`oc_close`)";
						
						
						
						
			$return = "($today_query AND ($today_time)) OR ($yesterday_query AND ($yesterday_time))";
						
			break;
	}
	return $return;
}
function cn_scheduling_update_data($args) {
	global $cndb;
	$data = $args['form_fields'];
	$listing = $args['listing_id'];
	$repeat_schedules = array();
	$openclose_schedules = array();
	foreach($data as $column=>$value) {
		
		if(strstr($column, 'cn_scheduling_repeat')) {
			$column = str_replace('cn_scheduling_repeat_', '', $column);
			$repeat_schedules[$column] = $value;
		}
		elseif(strstr($column, 'cn_scheduling_open_close')) {
			$column = str_replace('cn_scheduling_open_close_', '', $column);
			$oc_schedules[$column] = $value;
		}
	}
	if($count = count($repeat_schedules['rptstart'])) {
		/** Go through each repeat schedule and see if it's new (it's new if it doesn't match any current repeat schedules for that listing). If yes, add it and populate occurrences the same way as insertion. If no, keep it the same and mark that it's still there. */
		$schedules = $cndb->get_results("SELECT `rpt_id` FROM `cn_rpt_schedules` WHERE `rpt_listing`='$listing'");
		$current_schedules = array();
		foreach($schedules as $schedule) {
			$current_schedules[$schedule->rpt_id] = $schedule->rpt_id;
		}
		
		/** Insert repeat schedule into schedules table */
		$insert_data = array();
		$insert_data['rpt_mode'] = $repeat_schedules['rptmode'];
		$insert_data['rpt_start'] = $repeat_schedules['rptstart'];
		$insert_data['rpt_end'] = $repeat_schedules['rptend'];
		$insert_data['rpt_listing'] = $listing;
		$insert_data['rpt_for'] = $repeat_schedules['rptfor'];
		$insert_data['rpt_unit'] = $repeat_schedules['rptunit'];
		for($i=0;$i<$count;$i++) {
			$data = array('rpt_mode'=>$insert_data['rpt_mode'][$i], 'rpt_start'=>$insert_data['rpt_start'][$i], 'rpt_end'=>$insert_data['rpt_end'][$i], 'rpt_listing'=>$insert_data['rpt_listing'], 'rpt_for'=>$insert_data['rpt_for'][$i], 'rpt_unit'=>$insert_data['rpt_unit'][$i]);
			if($schedule_id = $cndb->get_var("SELECT `rpt_id` FROM `cn_rpt_schedules` WHERE `rpt_mode`='".$data['rpt_mode']."' AND `rpt_start`='".$data['rpt_start']."' AND `rpt_end`='".$data['rpt_end']."' AND `rpt_for`='".$data['rpt_for']."' AND `rpt_unit`='".$data['rpt_unit']."' AND `rpt_listing`='$listing'")) {
				unset($current_schedules[$schedule_id]);
			}
			else {
				$cndb->insert('cn_rpt_schedules', $data);
			}
		}
		
		$deleted_schedules = "'".implode("', '", $current_schedules)."'";
		$cndb->query("DELETE FROM `cn_rpt_schedules` WHERE `rpt_id` IN ($deleted_schedules)");
		$cndb->query("DELETE FROM `cn_rpt_occurrences` WHERE `occurrence_schedule` IN ($deleted_schedules)");
		cn_scheduling_populate_occurrences($listing);
		
	}
	else {
		/** No repeat schedules anymore, so we delete all schedules and occurrences for this listing */
		$cndb->query("DELETE FROM `cn_rpt_schedules` WHERE `rpt_listing`='$listing'");
		$cndb->query("DELETE FROM `cn_rpt_occurrences` WHERE `occurrence_listing`='$listing'");
	}
	
	if($count = count($oc_schedules['open'])) {
		/** Go through each open/close schedule and see if it's new (it's new if it doesn't match any current open/close schedules for that listing). */
		$schedules = $cndb->get_results("SELECT `oc_id` FROM `cn_open_close_schedules` WHERE `oc_listing`='$listing'");
		$current_schedules = array();
		foreach($schedules as $schedule) {
			$current_schedules[$schedule->oc_id] = $schedule->oc_id;
		}
		
		/** Insert repeat schedule into schedules table */
		$insert_data = array();
		$insert_data['open'] = $oc_schedules['open'];
		$insert_data['close'] = $oc_schedules['close'];
		$insert_data['days'] = $oc_schedules['days'];
		$insert_data['listing'] = $listing;
		for($i=0;$i<$count;$i++) {
			$data = array('oc_open'=>$insert_data['open'][$i], 'oc_close'=>$insert_data['close'][$i], 'oc_days'=>$insert_data['days'][$i], 'oc_listing'=>$listing);
			if($schedule_id = $cndb->get_var("SELECT `oc_id` FROM `cn_open_close_schedules` WHERE `oc_open`='".$data['oc_open']."' AND `oc_close`='".$data['oc_close']."' AND `oc_days`='".$data['oc_days']."' AND `oc_listing`='$listing'")) {
				unset($current_schedules[$schedule_id]);
			}
			else {
				$cndb->insert('cn_open_close_schedules', $data);
			}
		}
		
		$deleted_schedules = "'".implode("', '", $current_schedules)."'";
		$cndb->query("DELETE FROM `cn_open_close_schedules` WHERE `oc_id` IN ($deleted_schedules)");
	}
	else {
		/** No repeat schedules anymore, so we delete all schedules and occurrences for this listing */
		$cndb->query("DELETE FROM `cn_open_close_schedules` WHERE `oc_listing`='$listing'");
	}
	
}
function cn_scheduling_insert_data($args) {
	global $cndb;
	$data = $args['form_fields'];
	$insert_id = $args['listing_id'];
	$repeat_schedules = array();
	$oc_schedules = array();
	foreach($data as $column=>$value) {
		if(strstr($column, 'cn_scheduling_repeat')) {
			$column = str_replace('cn_scheduling_repeat_', '', $column);
			$repeat_schedules[$column] = $value;
		}
		elseif(strstr($column, 'cn_scheduling_open_close')) {
			$column = str_replace('cn_scheduling_open_close_', '', $column);
			$oc_schedules[$column] = $value;
		}
	}
	
	if($count = count($repeat_schedules['rptstart'])) {
		/** Insert repeat schedule into schedules table */
		$insert_data = array();
		$insert_data['rpt_mode'] = $repeat_schedules['rptmode'];
		$insert_data['rpt_start'] = $repeat_schedules['rptstart'];
		$insert_data['rpt_end'] = $repeat_schedules['rptend'];
		$insert_data['rpt_listing'] = $insert_id;
		$insert_data['rpt_for'] = $repeat_schedules['rptfor'];
		$insert_data['rpt_unit'] = $repeat_schedules['rptunit'];
		
		for($i=0;$i<$count;$i++) {
			$data = array('rpt_mode'=>$insert_data['rpt_mode'][$i], 'rpt_start'=>$insert_data['rpt_start'][$i], 'rpt_end'=>$insert_data['rpt_end'][$i], 'rpt_listing'=>$insert_data['rpt_listing'], 'rpt_for'=>$insert_data['rpt_for'][$i], 'rpt_unit'=>$insert_data['rpt_unit'][$i]);
			$cndb->insert('cn_rpt_schedules', $data);
		}
		cn_scheduling_populate_occurrences($insert_id);
	}
	if($count = count($oc_schedules['open'])) {
		/** Insert open/close schedule into schedules table */
		$insert_data['open'] = $oc_schedules['open'];
		$insert_data['close'] = $oc_schedules['close'];
		$insert_data['days'] = $oc_schedules['days'];
		for($i=0;$i<$count;$i++) {
			$data = array('oc_open'=>$insert_data['open'][$i], 'oc_close'=>$insert_data['close'][$i], 'oc_days'=>$insert_data['days'][$i], 'oc_listing'=>$insert_id);
			$cndb->insert('cn_open_close_schedules', $data);
		}
	}
}

function cn_scheduling_populate_occurrences($listing_id, $mode = 'insert') {
	global $cndb;
	$cndb->query("DELETE FROM `cn_rpt_occurrences` WHERE `occurrence_listing`='$listing_id'");
	$repeat_schedules = $cndb->get_results("SELECT *, DATEDIFF(NOW(), `rpt_start`) AS `day_diff`, (MONTH(NOW()) - MONTH(`rpt_start`)) + ((YEAR(NOW()) - YEAR(`rpt_start`))*12) AS `month_diff` FROM `cn_rpt_schedules` WHERE `rpt_listing`='$listing_id'");
	
	
	
	
	foreach($repeat_schedules as $schedule) {
		/** Add occurrences for up to a year in the future */
		$start = $schedule->rpt_start;
		$end = $schedule->rpt_end;
		
		/** Add occurrences to occurrences table. Right now we add up 1 year in the future. Could change, depending upon database performance. */
		$day_multiplier = 0;
		$month_multiplier = 0;
		$year_multiplier = 0;
		
		switch($schedule->rpt_mode) {
			/*case 'daily':
				$day_multiplier = 1;
				break;
			case 'weekly':
				$day_multiplier = 7;
				break;
			case 'biweekly':
				$day_multiplier = 14;
				break;*/
			case 'monthly_day':
				$month_multiplier = 1;
				break;
			case 'monthly_nth':
				$month_multiplier = 'monthly_nth';
				break;
				
			/*case 'bimonthly':
				$month_multiplier = 2;
				break;
			case 'quarterly':
				$month_multiplier = 3;
				break;
			case 'halfyearly':
				$month_multiplier = 6;
				break;*/
			case 'yearly':
				$year_multiplier = 1;
				break;
			default:
				if($schedule->rpt_mode) $day_multiplier = 7;
				break;
		
		}
	
		if($day_multiplier) {
			if($mode == 'insert') $min = 0;
			else $min = $schedule->day_diff;
			
			$max = $schedule->day_diff + 365;
			if($min < 0) $min = 0;
			if($max < 0) $max = 0;
			
				
			/** Get the nearest ___day to start, and run for each day */
			$dates = array();
			$main_day = strtolower(date('w', strtotime($start)));
			$day_differences = array('sun'=>(0 - $main_day), 'mon'=>(1 - $main_day), 'tue'=>(2 - $main_day), 'wed'=>(3 - $main_day), 'thu'=>(4 - $main_day), 'fri'=>(5 - $main_day), 'sat'=>(6 - $main_day));
				
			foreach($day_differences as $day=>$diff) {
				if($diff < 0) $diff = $diff + 7;
				if(strstr($schedule->rpt_mode, $day)) {
					$start_date = date('Y-m-d H:i:s', strtotime($start) + 60*60*24*$diff);
					$end_date = date('Y-m-d H:i:s', strtotime($end) + 60*60*24*$diff);
					for($i=$min;$i< $max;$i += $day_multiplier) {
						if(!$cndb->get_count("SELECT `occurrence_id` FROM `cn_rpt_occurrences` WHERE `occurrence_schedule`='$schedule->rpt_id' AND `occurrence_start`=DATE_ADD('$start_date', INTERVAL $i DAY)") && $cndb->get_var("SELECT DATE_ADD('$start', INTERVAL $schedule->rpt_for $schedule->rpt_unit) >= DATE_ADD('$start_date', INTERVAL $i DAY) OR $schedule->rpt_for = '0'")) {
							mysql_query("INSERT INTO `cn_rpt_occurrences` (`occurrence_schedule`, `occurrence_listing`, `occurrence_end`, `occurrence_start`) VALUES('$schedule->rpt_id', '$schedule->rpt_listing', DATE_ADD('$end_date', INTERVAL $i DAY), DATE_ADD('$start_date', INTERVAL $i DAY))");
						}
					}
				}
				
				
			}
		}
		elseif($month_multiplier == 'monthly_nth') {
			/** Get the day and nth values of the starting date */
			$day = date('w', strtotime(str_replace('-', '/', $start))) + 1;
			$nth = floor(date('j', strtotime(str_replace('-', '/', $start))) / 7);
			
			if($mode == 'insert') $min = 0;
			else $min = $schedule->month_diff;
			$max = $schedule->month_diff + 12;
			if($min < 0) $min = 0;
			if($max < 0) $max = 0;
			$sdate = strtotime(str_replace('-', '/', $start));
			
			$edate = strtotime(str_replace('-', '/', $end));
			
			$starttime = mktime(date('H', $sdate), date('i', $sdate), date('s', $sdate), date('n', $sdate), 1, date('Y', $sdate));
			$endtime = mktime(date('H', $edate), date('i', $edate), date('s', $edate), date('n', $edate), 1, date('Y', $edate));
			
			if($endtime <= $starttime) {
				$endtime = $endtime + 60*60*24;
			}
			$month_multiplier = 1;
			
			$starttime = date('Y-m-d H:i:s', $starttime);
			$endtime = date('Y-m-d H:i:s', $endtime);
			for($i=$min;$i<$max;$i += $month_multiplier) {
				if(!$cndb->get_count("SELECT `occurrence_id` FROM `cn_rpt_occurrences` WHERE `occurrence_schedule`='$schedule->rpt_id' AND `occurrence_start`=DATE_ADD(DATE_ADD('$starttime', INTERVAL $i MONTH), INTERVAL ((7 * $nth) - ((6 - $day + DAYOFWEEK(DATE_ADD('$starttime', INTERVAL $i MONTH))) % 7) - 1) DAY) AND `occurrence_end`=DATE_ADD(DATE_ADD('$endtime', INTERVAL $i MONTH), INTERVAL ((7 * '$nth') - ((6 - '$day' + DAYOFWEEK(DATE_ADD('$endtime', INTERVAL $i MONTH))) % 7) - 1) DAY)") && $cndb->get_var("SELECT DATE_ADD('$start', INTERVAL $schedule->rpt_for $schedule->rpt_unit) >= DATE_ADD(DATE_ADD('$starttime', INTERVAL $i MONTH), INTERVAL ((7 * $nth) - ((6 - $day + DAYOFWEEK(DATE_ADD('$starttime', INTERVAL $i MONTH))) % 7) - 1) DAY) OR $schedule->rpt_for = '0'")) {
					mysql_query("INSERT INTO `cn_rpt_occurrences` (`occurrence_schedule`, `occurrence_listing`, `occurrence_end`, `occurrence_start`) VALUES('$schedule->rpt_id', '$schedule->rpt_listing', DATE_ADD(DATE_ADD('$endtime', INTERVAL $i MONTH), INTERVAL ((7 * $nth) - ((6 - $day + DAYOFWEEK(DATE_ADD('$starttime', INTERVAL $i MONTH))) % 7) - 1) DAY), DATE_ADD(DATE_ADD('$starttime', INTERVAL $i MONTH), INTERVAL ((7 * $nth) - ((6 - $day + DAYOFWEEK(DATE_ADD('$starttime', INTERVAL $i MONTH))) % 7) - 1) DAY))");
				}
			}
		}
		elseif($month_multiplier) {
			if($mode == 'insert') $min = 0;
			else $min = $schedule->month_diff;
			$max = $schedule->month_diff + 12;
			if($min < 0) $min = 0;
			if($max < 0) $max = 0;
			$datetime = date('Y-m-d H:i:s', $date);
			for($i=$min;$i<$max;$i += $month_multiplier) {
				if(!$cndb->get_count("SELECT `occurrence_id` FROM `cn_rpt_occurrences` WHERE `occurrence_schedule`='$schedule->rpt_id' AND `occurrence_start`=DATE_ADD('$start', INTERVAL $i MONTH)")  && $cndb->get_var("SELECT 'TRUE' as `result` WHERE DATE_ADD('$start', INTERVAL $schedule->rpt_for $schedule->rpt_unit) >= DATE_ADD('$start', INTERVAL $i MONTH)) OR $schedule->rpt_for = '0'")) {
					mysql_query("INSERT INTO `cn_rpt_occurrences` (`occurrence_schedule`, `occurrence_listing`, `occurrence_end`, `occurrence_start`) VALUES('$schedule->rpt_id', '$schedule->rpt_listing', DATE_ADD('$end', INTERVAL $i MONTH), DATE_ADD('$start', INTERVAL $i MONTH))");
				}
			}
		}
		elseif($year_multiplier) {
			$diff = $schedule->day_diff;
			$year_diff = floor($diff/365);
			if($cndb->get_var("SELECT 'TRUE' as `result` WHERE DATE_ADD('$start', INTERVAL $schedule->rpt_for $schedule->rpt_unit) >= DATE_ADD('$start', INTERVAL $year_diff YEAR) OR $schedule->rpt_for = '0'")) {
				mysql_query("INSERT INTO `cn_rpt_occurrences` (`occurrence_schedule`, `occurrence_listing`, `occurrence_end`, `occurrence_start`) VALUES('$schedule->rpt_id', '$schedule->rpt_listing', DATE_ADD('$end', INTERVAL $year_diff YEAR), DATE_ADD('$start', INTERVAL $year_diff YEAR))");
			}
		}
		else {
			mysql_query("INSERT INTO `cn_rpt_occurrences` (`occurrence_schedule`, `occurrence_listing`, `occurrence_end`, `occurrence_start`) VALUES('$schedule->rpt_id', '$schedule->rpt_listing', '$end', '$start')");
		}
	}
}


?>